package database

import (
	"blog2/util"
	"time"

	"gorm.io/gorm"
)

type Blog struct {
	Id         int       `gorm:"column:id;primaryKey"`
	UserId     int       `gorm:"column:user_id"`
	Title      string    `gorm:"column:title"`
	Article    string    `gorm:"column:article"`
	UpdateTime time.Time `gorm:"column:update_time"`
}

func (Blog) TableName() string {
	return "blog"
}

var (
	_all_blog_fields = util.GormFields(Blog{})
)

func CreateBlog(userId int, title, article string) error {
	db := GetBlogDBConnection()
	if err := db.Create(&Blog{UserId: userId, Title: title, Article: article, UpdateTime: time.Now()}).Error; err != nil {
		util.LogRus.Errorf("Error creating blog, userId: %d, title: %s, article: %s", userId, title, article)
		return err
	} else {
		util.LogRus.Infof("Blog %s created successfully", title)
		return nil
	}
}

func GetBlogByTitleAndUserId(userId int, title string) *Blog {
	db := GetBlogDBConnection()
	var blog Blog
	if err := db.Select(_all_blog_fields).Where("user_id=? AND title=?", userId, title).First(&blog).Error; err != nil {
		if err != gorm.ErrRecordNotFound {
			util.LogRus.Infof("Error getting blog by title and user id: %d, %s, error: %s", userId, title, err)
		}
		return nil
	} else {
		util.LogRus.Infof("Get blog by title and user id success: %v", blog)
		return &blog
	}
}

func DeleteBlogByTitleAndUserId(userId int, title string) error {
	db := GetBlogDBConnection()
	if err := db.Where("user_id=? AND title=?", userId, title).Delete(Blog{}).Error; err != nil {
		util.LogRus.Infof("delete blog by title and user id %d, %s failed: %s", userId, title, err)
		return err
	}
	return nil
}

func DeleteBlogByBlogId(blogId int) error {
	db := GetBlogDBConnection()
	if err := db.Where("id=?", blogId).Delete(Blog{}).Error; err != nil {
		util.LogRus.Infof("delete blog by id %d failed: %s", blogId, err)
		return err
	}
	return nil
}

func UpdateBlogTitle(userId int, title, newTitle string) error {
	db := GetBlogDBConnection()
	if err := db.Model(&Blog{}).Where("user_id=? AND title=?", userId, title).Update("title", newTitle).Error; err != nil {
		util.LogRus.Infof("update blog title %d, %s failed: %s", userId, title, err)
		return err
	}
	return nil
}

func UpdateBlogArticle(userId int, title, newArticle string) error {
	db := GetBlogDBConnection()
	if err := db.Model(&Blog{}).Where("user_id=? AND title=?", userId, title).Update("article", newArticle).Error; err != nil {
		util.LogRus.Infof("update blog article %d, %s failed: %s", userId, title, err)
		return err
	}
	return nil
}

func GetBlogListByUserId(userId int) ([]Blog, error) {
	db := GetBlogDBConnection()
	blogs := make([]Blog, 0)
	if err := db.Model(&Blog{}).Where("user_id=?", userId).Find(&blogs).Error; err != nil {
		util.LogRus.Infof("Error getting blog list by user id: %d, error: %s", userId, err)
		return nil, err
	}
	return blogs, nil
}
